package com.ymy.boot.aqs;

/**
 * LockSupport:
 * 1. 只阻塞和唤醒线程, 不用先拿到锁
 * 2. park(): 阻塞线程; unPark(): 解除线程阻塞
 * 3. park() unPark() 没有先后顺序
 *
 * @author Ringo
 * @date 2021/4/19 16:59
 */
public class NoReentrantDemo {

    public static void main(String[] args) {

        Resource resource = new Resource();

        for (int i = 0; i < 10; ++i) {
            new Thread(() -> {
                for (int j = 0; j < 5000; ++j) {
                    // Thread safe
                    resource.aqsDecrease();

                    // Thread safe
                    // resource.decrease();
                }
            }).start();
        }

        while (Thread.activeCount() > 2) {
            Thread.yield();
        }

        System.out.println(resource.number);

    }

    public static class Resource {
        // LockSupport 实现的锁
        LockSupportNonReentrantLock lock1 = new LockSupportNonReentrantLock();
        // AQS 实现的锁
        AQSNonReentrantLock lock2 = new AQSNonReentrantLock();

        private int number = 10_0000;

        public void aqsDecrease() {
            try {
                lock2.lock();
                --number;
            } finally {
                lock2.unlock();
            }
        }

        public void decrease() {
            try {
                lock1.lock();
                --number;
            } finally {
                lock1.unlock();
            }
        }
    }

}
